import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref('')

  // 登录方法
  const login = async (adminName, password) => {
    try {
      const res = await loginApi(adminName, password)
      if (res.code === 1 && res.data?.code === 1) {
        // 保存token到本地存储和store
        token.value = res.data.data
        localStorage.setItem('token', res.data.data)
        return true
      }
      return false
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 登出方法
  const logout = () => {
    token.value = ''
    username.value = ''
    localStorage.removeItem('token')
  }

  return {
    token,
    username,
    login,
    logout
  }
}) 